﻿picShare.service('httpRequestSvc', function () {

    var httpRootUserUrl = "http://localhost:26666/api/users/";
    var httpRootImageUrl = "http://localhost:26666/api/image/";

    var promiseAjaxRequest = function (url, type, data, sessionKey) {
        var ajaxDeferred = Q.defer();

        if (data) {
            data = JSON.stringify(data);
        }

        if (sessionKey == undefined) {
            sessionKey = null;
        }

        $.ajax({
            url: url,
            type: type,
            data: data,
            headers: { "X-SessionKey": sessionKey },
            contentType: "application/json",
            success: function (responseData) {
                ajaxDeferred.resolve(responseData);
            },
            error: function (errorData) {
                ajaxDeferred.reject(errorData);
            }
        });

        return ajaxDeferred.promise;
    };

    var promiseAjaxImageRequest = function (url, type, data, sessionKey) {
        var ajaxDeferred = Q.defer();

        if (sessionKey == undefined) {
            sessionKey = null;
        }

        $.ajax({
            url: url,
            type: type,
            data: data,
            headers: { "X-SessionKey": sessionKey },
            cache: false,
            contentType: false,
            processData: false,
            success: function (responseData) {
                ajaxDeferred.resolve(responseData);
            },
            error: function (errorData) {
                ajaxDeferred.reject(errorData);
            }
        });

        return ajaxDeferred.promise;
    };

    var promiseAjaxRequestGet = function (url) {
        return promiseAjaxRequest(url, "get");
    };

    var promiseAjaxRequestPost = function (url, data) {
        return promiseAjaxRequest(url, "post", data);
    };

    var promiseAjaxRequestPut = function (url, data, sessionKey) {
        return promiseAjaxRequest(url, "put", data, sessionKey);
    };

    var promiseAjaxImage = function (url, data, sessionKey) {
        return promiseAjaxImageRequest(url, "post", data, sessionKey);
    };

    return {
        getJson: promiseAjaxRequestGet,
        postJson: promiseAjaxRequestPost,
        putJson: promiseAjaxRequestPut,
        postImage: promiseAjaxImage,
        httpRootUserUrl: httpRootUserUrl,
        httpRootImageUrl: httpRootImageUrl
    };
});